package org.example.leetCode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
public class MajorityElement {

    //Map解法
    public int majorityElement1(int[] nums) {
        int length = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.merge(num, 1, Integer::sum);
            if (map.get(num) > length / 2) {
                return num;
            }
        }
        return -1;
    }

    //排序解法
    public int majorityElement2(int[] nums) {
        int length = nums.length;
        int left = 0;
        int right = length - 1;
        quickSort(nums, left, right);
        return nums[length / 2];
    }

    static void quickSort(int[] arr, int begin, int end) {
        if (begin >= end) {
            return;
        }
        int temp = arr[begin];
        int m = begin + 1;
        int n = end;

        while (m < n) {
            while (temp > arr[m] && m < n) {
                m++;
            }
            while (temp < arr[n] && m < n) {
                n--;
            }
            int exc = arr[m];
            arr[m] = arr[n];
            arr[n] = exc;
        }
        arr[begin] = arr[m];
        arr[m] = temp;
        quickSort(arr, begin, m - 1);
        quickSort(arr, m + 1, end);
    }
}
